/*
This file contains code derived from the hyperledger fabric(https://github.com/hyperledger/fabric)
The original code is licensed under the Apache 2.0 license (http://www.apache.org/licenses/LICENSE-2.0)
We have made necessary modifications to the original code to meet the needs of this project and have included our own additional code here.

The copyright for the modifications and derivative works belongs to Inspur and was made in 2022.
Subject to the terms and conditions of the Apache 2.0 License for fabric, these modifications and derivative works are also distributed under the Apache 2.0 License.
Please note that these modifications and derivative works do not provide any warranty for fabric, and the use of them is at the user's own risk.
*/

package etcdraft

import (
	"fmt"
	"io/ioutil"

	"github.com/golang/protobuf/proto"
)

const TypeKey = "etcdraft"

// ConsensusTypeMetadataFactory allows this implementation's proto messages to register
// their type with the consenser's proto messages. This is needed for protolator to work.
type ConsensusTypeMetadataFactory struct{}

// NewMessage implements the Consenser.ConsensusTypeMetadataFactory interface.
func (dogf ConsensusTypeMetadataFactory) NewMessage() proto.Message {
	return &ConfigMetadata{}
}

// Marshal serializes this implementation's proto messages. It is called by the encoder package
// during the creation of the Orderer ConfigGroup.
func Marshal(md *ConfigMetadata) ([]byte, error) {
	copyMd := proto.Clone(md).(*ConfigMetadata)
	for _, c := range copyMd.Consensers {
		// Expect the user to set the config value for client/server certs to the
		// path where they are persisted locally, then load these files to memory.
		clientCert, err := ioutil.ReadFile(string(c.GetClientTlsCert()))
		if err != nil {
			return nil, fmt.Errorf("cannot load client cert for consenser %s:%d: %s", c.GetHost(), c.GetPort(), err)
		}
		c.ClientTlsCert = clientCert

		serverCert, err := ioutil.ReadFile(string(c.GetServerTlsCert()))
		if err != nil {
			return nil, fmt.Errorf("cannot load server cert for consenser %s:%d: %s", c.GetHost(), c.GetPort(), err)
		}
		c.ServerTlsCert = serverCert
	}
	return proto.Marshal(copyMd)
}